package com.edu.util;

import com.edu.HandlerDefinition;
import com.edu.ScanUtil;
import com.edu.interceptor.Interceptor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


/**
 * 存放方法和实例
 */
public class HandlerDefinitionParser {

    private static List<String> list = ScanUtil.scanPackage();
    /**
     * 收集方法和实例
     * @return
     */
    public static List<HandlerDefinition> parseDifinition(){
        List<HandlerDefinition> result = new ArrayList<>();
        for (String className:list){
            Class<?> clz = createHandlerClass(className);
            Method[] methods = clz.getDeclaredMethods();
            for (Method m:methods){
                HandlerDefinition definition = new HandlerDefinition();
                definition.setClazz(clz);
                definition.setMethod(m);
                result.add(definition);
            }

        }
        return result;
    }

    public static List<Class<?>> parseInterceptor(){
        List<Class<?>> result = new ArrayList<>();
        for (String className:list){
            Class<?> interceptorClass = createHandlerClass(className);
            if (interceptorClass!=null&& Interceptor.class.isAssignableFrom(interceptorClass)){
                result.add(interceptorClass);
            }
        }
        return result;
    }

    /**
     * 字符串转换成实例
     *
     * @param className
     * @return
     */
    private static Class<?> createHandlerClass(String className){
        Class<?> clz = null;
        try {
            clz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return clz;
    }

}
